//
//  TGNetworkManager.m
//  指乎
//
//  Created by Dean on 16/6/13.
//  Copyright © 2016年 Dean. All rights reserved.
//
#import "TGNetworkManager.h"
#import "TGLocationReachability.h"
#import "TGRealReachability.h"
#import "TGURLMacros.h"
#import "LoginVC.h"
#import "UIImage-Extension.h"
#import "NSString+MD5.h"
//#import "AppDelegate+JPush.h"

@implementation TGNetworkManager
+ (instancetype)sharedClient {
    static TGNetworkManager *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *url = nil;

//        NSString *testUrl = [[NSUserDefaults standardUserDefaults] objectForKey:@"testUrl"];
//        if (!EmptyCheck(testUrl)) {
//            url = testUrl;
//        }else {
            url = APP_URL;
//        }
        _sharedClient = [[TGNetworkManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
        _sharedClient.responseSerializer = [AFJSONResponseSerializer serializer];
        _sharedClient.requestSerializer  = [AFHTTPRequestSerializer serializer];
        //        _sharedClient.responseSerializer.acceptableContentTypes =  [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml",@"text/html", @"application/json",@"text/plain", nil];
        //        _sharedClient.responseSerializer.acceptableContentTypes = nil;
        
    });
    return _sharedClient;
}
+ (instancetype)sharedJsonClient {
    static TGNetworkManager *_sharedJsonClient = nil;
    static dispatch_once_t onceToken1;
    dispatch_once(&onceToken1, ^{
        NSString *url = nil;
//        NSString *testUrl = [[NSUserDefaults standardUserDefaults] objectForKey:@"testUrl"];
//        if (!EmptyCheck(testUrl)) {
//            url = testUrl;
//        }else {
            url = APP_URL;
//        }
        
        _sharedJsonClient = [[TGNetworkManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
        _sharedJsonClient.responseSerializer = [AFJSONResponseSerializer serializer];
        _sharedJsonClient.requestSerializer  = [AFJSONRequestSerializer serializer];
        //        _sharedJsonClient.responseSerializer.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml",@"text/html", @"application/json",@"text/plain", nil];
    });
    return _sharedJsonClient;
}
+ (TGNetworkManager *)managerRequest:(NSString *)url isJsonReponse:(BOOL)isJsonReponse postHeadParameterMD5:(NSString*)md5Str {
    TGNetworkManager *m = nil;
    if (isJsonReponse) {
        m = [self sharedJsonClient];
    } else {
        m = [self sharedClient];
    }
    [m.requestSerializer setValue:@"gzip,br" forHTTPHeaderField:@"Accept-Encoding"];
//    if (!PCBStringIsEmpty(md5Str))
//    {
//        [m.requestSerializer setValue:md5Str forHTTPHeaderField:@"X-Request-Body-Sign"];
//    }
    [m.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    m.requestSerializer.timeoutInterval = 5;
    [m.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    [m.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@", TGUserModel.getUserEntity.getToken] forHTTPHeaderField:@"Authorization"];

    
    /***  系统，版本，机型*/
    //        [m.requestSerializer setValue:@"ios" forHTTPHeaderField:@"os"];
    //        [m.requestSerializer setValue:R([[UIDevice currentDevice] systemVersion]) forHTTPHeaderField:@"osVersion"];
    return m;
}

/**
 *	取消所有请求
 */
+ (void)cancelAllRequest {
    //    @synchronized(self) {
    //        [[self allTasks] enumerateObjectsUsingBlock:^(NSURLSessionDataTask * _Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
    //            if ([task isKindOfClass:[NSURLSessionDataTask class]]) {
    //                [task cancel];
    //            }
    //        }];
    //        [[self allTasks] removeAllObjects];
    //    };
}
+ (void)cancelRequestWithURL:(NSString *)url{
    if (url == nil) {
        return;
    }
    @synchronized(self) {
        [[self allTasks] enumerateObjectsUsingBlock:^(NSURLSessionDataTask * _Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([task isKindOfClass:[NSURLSessionDataTask class]]
                && [task.currentRequest.URL.absoluteString hasSuffix:url]) {
                [task cancel];
                [[self allTasks] removeObject:task];
                return;
            }
        }];
    };
}

+ (AFSecurityPolicy*)customSecurityPolicy
{
    // /先导入证书
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"lzt" ofType:@"cer"];
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName =  NO;
    securityPolicy.pinnedCertificates = [NSSet setWithObjects:certData, nil];
    return securityPolicy;
}

+ (NSDictionary *)parametserToJson:(NSMutableDictionary *)dict {
    if (dict == nil) {
        return nil;
    }
    if ([dict isKindOfClass:[NSString class]]) {
        return @{@"param":R(dict)};
    }
    return @{@"param":R([dict objectToJSON])};
}
+(NSString *)addCommontURLPrefix:(NSString*)oldUrl {
    if ([oldUrl isEqualToString:@"api/login"]) {
        return oldUrl;
    }
    //    return [NSString stringWithFormat:@"crm-service%@", oldUrl];
    //    return [NSString stringWithFormat:@"contract-service%@", oldUrl];
    return oldUrl;
}

+ (NSURLSessionDataTask *)GETWithURLString:(NSString *)URLString
                                parameters:(id)parameters
                                   success:(LZTResponseSuccess)success
                                   failure:(LZTResponseFailure)failure {
    return [self GETWithURLString:URLString header:nil parameters:parameters success:success failure:failure];
}


+ (NSURLSessionDataTask *)GETWithURLString:(NSString *)URLString
                                    header:(NSDictionary <NSString *, NSString *>*)header
                                parameters:(NSDictionary *)parameters
                                   success:(LZTResponseSuccess)success
                                   failure:(LZTResponseFailure)failure {
    WEAK
    AFHTTPSessionManager *magnager = [self managerRequest:URLString isJsonReponse:NO postHeadParameterMD5:@""];
    URLString  = [self package:URLString mamager:magnager parameters:parameters];
    NSURLSessionDataTask *dataTask = nil;
    if(![self networkisReachable]){
        if (failure) {
            failure(nil);
        }
        return nil;
    }
    
    dataTask =  [magnager GET:URLString parameters:parameters headers:header progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        STRONG
        //         NSURLRequest *org = (NSURLRequest *)task.originalRequest;
        //         NSLog(@"原始的请求头%@",org.allHTTPHeaderFields);
        //         NSURLRequest *curreq = (NSURLRequest *)task.currentRequest;
        //         NSLog(@"当前的请求头%@",curreq.allHTTPHeaderFields);
        //        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        //        NSLog(@"0---0%@",response.allHeaderFields);
        //         if ([response.allHeaderFields objectForKey:@"Content-Encoding"]) {
        //             [LDProgressHUD showHUDTip:@"开启了gzip 压缩"];
        //             NSLog(@"开启了gzip 压缩");
        //         }
        NSLog(@"url = %@ \n response = %@", URLString, [responseObject objectToJSON]);
   
        
        TGResponseItem *responseItem = [TGResponseItem modelWithDictionary:responseObject];
        if (responseItem.status == 401) {
            
            [self showLoginWithComplemention:^(NSString *result) {
                
//                if ([result isEqualToString:@"1"]) {
//
//                    AFHTTPSessionManager *magnagerNew = [self managerRequest:URLString isJsonReponse:NO postHeadParameterMD5:@""];
//
//                    [magnagerNew GET:URLString parameters:parameters headers:header progress:^(NSProgress * _Nonnull downloadProgress) {
//
//                    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//
//                        TGResponseItem *responseItemNew = [TGResponseItem modelWithDictionary:responseObject];
//                        if (!responseItemNew.success && !EmptyCheck(responseItemNew.message)) {
//                            [TGGCD executeAfterTime:0.5 task:^{
//                                [TGProgressHUD showMBHUDErrorTip:responseItemNew.message];
//                            }];
//                        }
//                        [self successResponse:responseItemNew callback:success];
//                        [[self allTasks] removeObject:dataTask];
//
//                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                        STRONG
//                        [self faileureShowTip:failure error:error];
//                        [[self allTasks] removeObject:dataTask];
//                    }];
//                }
                [self successResponse:responseItem callback:success];
                [[self allTasks] removeObject:task];
            }];
            
        } else {
            if (!responseItem.success && !EmptyCheck(responseItem.message)) {
                [TGGCD executeAfterTime:0.5 task:^{
                    [TGProgressHUD showMBHUDErrorTip:responseItem.message];
                }];
            }
            [self successResponse:responseItem callback:success];
            [[self allTasks] removeObject:dataTask];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        STRONG
        [self faileureShowTip:failure error:error];
        [[self allTasks] removeObject:dataTask];
    }];
    
    if (dataTask) {
        [[self allTasks] addObject:dataTask];
    }
    return dataTask;
}

+ (BOOL)getProxyStatus {
    NSDictionary *proxySettings =  (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings());
    NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:@"http://www.baidu.com"]), (__bridge CFDictionaryRef _Nonnull)(proxySettings)));
    NSDictionary *settings = [proxies objectAtIndex:0];
    
    NSLog(@"host=%@", [settings objectForKey:(NSString *)kCFProxyHostNameKey]);
    NSLog(@"port=%@", [settings objectForKey:(NSString *)kCFProxyPortNumberKey]);
    NSLog(@"type=%@", [settings objectForKey:(NSString *)kCFProxyTypeKey]);
    if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"]){
        //没有设置代理
        NSLog(@"没有设置代理");
        return NO;
    }else{
        //设置代理了
        NSLog(@"设置代理了");
        return YES;
    }
}
+ (BOOL) networkisReachable {
    
    if ([TGLocationReachability shareInstance].status == LC_UnReachable) {
        [TGGCD executeMainOpeation:^{
            [TGProgressHUD showHUDTip:@"网络连接出现异常了？\n 请检查您的网络连接"];
        }];
        return NO;
    }
    return YES;
}

+ (NSURLSessionDataTask *)POSTWithURLString:(NSString *)URLString
                                     header:(NSDictionary <NSString *, NSString *>*)header
                                 parameters:(NSDictionary *)parameters
                                    success:(LZTResponseSuccess)success
                                    failure:(LZTResponseFailure)failure {
    if(![self networkisReachable]){
        if (failure) {
            failure(nil);
        }
        return nil;
    }
    NSURLSessionDataTask *dataTask = nil;
    
    //将字典进行json转换
    NSString *jsonStr = [parameters objectToJSON];
    NSString *md5Str = [NSString md532BitLower:jsonStr];
    if ([URLString containsString:@"business/findCalculateTheRent"] ||
        [URLString containsString:@"queryByExitApplyIdAndEmptyAssociateData"] ||
        [URLString containsString:@"exitDeviceConfirm/queryByExitApplyId"]) {
        NSString *randomStr = [NSString stringWithFormat:@"%@%d", [NSString df_getCurrentTimestamp], arc4random()%1000];
        md5Str = [NSString md532BitLower:randomStr];
    }
    
    AFHTTPSessionManager *magnager = [self managerRequest:URLString isJsonReponse:YES postHeadParameterMD5:md5Str];
    URLString  = [self package:URLString mamager:magnager parameters:parameters];
    
    dataTask = [magnager
                POST:URLString
                parameters:parameters
                headers:header
                progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"url = %@ \n response = %@", URLString, [responseObject objectToJSON]);
        TGResponseItem *responseItem = [TGResponseItem modelWithDictionary:responseObject];
        if (responseItem.status == 401) {
            
            [self showLoginWithComplemention:^(NSString *result) {
//                NSString *randomStr = [NSString stringWithFormat:@"%@%d", [NSString df_getCurrentTimestamp], arc4random()%1000];
//                NSString *md5StrNew = [NSString md532BitLower:randomStr];
//                AFHTTPSessionManager *magnagerNew = [self managerRequest:URLString isJsonReponse:YES postHeadParameterMD5:md5StrNew];
//
//                [magnagerNew POST:URLString parameters:parameters headers:header progress:^(NSProgress * _Nonnull uploadProgress) {
//                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//
//                    TGResponseItem *responseItemNew = [TGResponseItem modelWithDictionary:responseObject];
//                    if (!responseItemNew.success && !EmptyCheck(responseItemNew.message)) {
//                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                            [TGProgressHUD showMBHUDErrorTip:responseItemNew.message];
//                        });
//                    }
//                    [self successResponse:responseItemNew callback:success];
//                    [[self allTasks] removeObject:task];
//
//                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                    [[self allTasks] removeObject:task];
//                }];
                [self successResponse:responseItem callback:success];
                [[self allTasks] removeObject:task];
            }];
            
            
        } else {
            if (!responseItem.success && !EmptyCheck(responseItem.message)) {
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [TGProgressHUD showMBHUDErrorTip:responseItem.message];
                });
            }
            [self successResponse:responseItem callback:success];
            [[self allTasks] removeObject:task];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [self faileureShowTip:failure error:error];
        [[self allTasks] removeObject:task];
    }];
    if (dataTask) {
        [[self allTasks] addObject:dataTask];
    }
    return dataTask;
}

+ (void)showLoginWithComplemention:(ComplentValueBlock)complemention {
//    // 刷新token
//    [TGUserModel refreshTokenWithComplemention:^(NSString *errorCode) {
//        if ([errorCode isEqualToString:@"GSE_003"] || [errorCode isEqualToString:@"0"]) {
//            //refreshtoken也失效
//            LoginVC *loginVC = [[LoginVC alloc] init];
//            loginVC.complentBlock = ^{
//                if (complemention) {
//                    complemention(@"1");
//                }
//            };
//            [(UITabBarController*)[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:loginVC animated:YES completion:nil];
//        } else {
//            if (complemention) {
//                complemention(@"1");
//            }
//        }
//    }];
 
    LoginVC *loginVC = [[LoginVC alloc] init];
    loginVC.complentBlock = ^{
        if (complemention) {
            complemention(@"1");
        }
        TGTabBarVC *tabarController = [[TGTabBarVC alloc] init];
        [[UIApplication sharedApplication].keyWindow setRootViewController:tabarController];
    };
    [[UIApplication sharedApplication].keyWindow setRootViewController:loginVC];
    
}

+ (NSString *)postDataWithDic:(NSDictionary *)dic {
    NSMutableString *dataStr = [NSMutableString string];
    for (int i = 0; i < dic.count;  i ++) {
        NSString *key = dic.allKeys[i];
        id value = dic[key];
        
        if ([value isKindOfClass:[NSString class]]) {
            [dataStr appendFormat:@"%@=%@&",key,value];
        }else if([value isKindOfClass:[NSDictionary class]]){
            
            NSDictionary *param = value;
            NSError *parseError = nil;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:&parseError];
            NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            [dataStr appendFormat:@"%@=%@&",key,jsonString];
        }
    }
    return dataStr;
}

+ (NSURLSessionDataTask *)POSTWithURLString:(NSString *)URLString
                                 parameters:(NSDictionary *)parameters
                                    success:(LZTResponseSuccess)success
                                    failure:(LZTResponseFailure)failure {
    
    return [self POSTWithURLString:URLString header:nil parameters:parameters success:success failure:failure];
}
+ (void)faileureShowTip:(LZTResponseFailure)failure error:(NSError *)error{
    if (failure) {
        [TGGCD executeAfterTime:0.5 task:^{
            [TGProgressHUD dismissMPHUD];
        }];
        NSLog(@"Request fail:%@",error);
        if (error.code == NSURLErrorCancelled) {
            failure(error);
            return;
        }
        else{
            //            [LZTGlobal showHUDTip:NetworkError];
            [TGProgressHUD showHUDTipNetError];
        }
        failure(error);
    }
}
/*!
 *  Delete请求接口，若不指定baseurl，可传完整的url
 *
 *  @param URLString     接口路径，如/path/getArticleList
 *  @param parameters  接口中所需的参数，如@{"categoryid" : @(12)}
 *  @param success 接口成功请求到数据的回调
 *  @param failure    接口请求数据失败的回调
 *
 *  @return 返回的对象中有可取消请求的API
 */
+ (NSURLSessionDataTask *)DELETEWithURLString:(NSString *)URLString
                                   parameters:(NSDictionary *)parameters
                                      success:(LZTResponseSuccess)success
                                      failure:(LZTResponseFailure)failure {
    NSURLSessionDataTask *dataTask = nil;
    if(![self networkisReachable]){
        if (failure) {
            failure(nil);
        }
        return nil;
    }
    AFHTTPSessionManager *magnager = [self managerRequest:URLString isJsonReponse:YES postHeadParameterMD5:@""];
    URLString  = [self package:URLString mamager:magnager parameters:parameters];
    if (parameters!=nil) {
        for (NSString *key in parameters.allKeys) {
            URLString = [URLString stringByAppendingFormat:@"/%@",parameters[key]];
        }
    }
    if(![self networkisReachable]){
        if (failure) {
            failure(nil);
        }
        return nil;
    }
    dataTask = [magnager DELETE:URLString parameters:nil headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"url = %@ \n response = %@", URLString, [responseObject objectToJSON]);
        TGResponseItem *responseItem = [TGResponseItem modelWithDictionary:responseObject];
        if (responseItem.status == 401) {
//            [self showLogin];
            [self showLoginWithComplemention:^(NSString *result) {
//                NSString *randomStr = [NSString stringWithFormat:@"%@%d", [NSString df_getCurrentTimestamp], arc4random()%1000];
//                NSString *md5StrNew = [NSString md532BitLower:randomStr];
//
//                AFHTTPSessionManager *magnagerNew = [self managerRequest:URLString isJsonReponse:YES postHeadParameterMD5:md5StrNew];
//
//                [magnagerNew DELETE:URLString parameters:nil headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//                    TGResponseItem *responseItemNew = [TGResponseItem modelWithDictionary:responseObject];
//                    if (!responseItemNew.success && !EmptyCheck(responseItemNew.message)) {
//                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                            [TGProgressHUD showMBHUDErrorTip:responseItemNew.message];
//                        });
//                    }
//                    [self successResponse:responseItemNew callback:success];
//                    [[self allTasks] removeObject:task];
//                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                    [[self allTasks] removeObject:task];
//                }];
                [self successResponse:responseItem callback:success];
                [[self allTasks] removeObject:task];
            }];
        } else {
            if (!responseItem.success && !EmptyCheck(responseItem.message)) {
                [TGGCD executeAfterTime:0.5 task:^{
                    [TGProgressHUD showMBHUDErrorTip:responseItem.message];
                }];
            }
            [self successResponse:responseItem callback:success];
            [[self allTasks] removeObject:task];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [self faileureShowTip:failure error:error];
        [[self allTasks] removeObject:task];
    }];
    if (dataTask) {
        [[self allTasks] addObject:dataTask];
    }
    return dataTask;
}

+ (NSURLSessionDataTask *)PUTWithURLString:(NSString *)URLString
                                parameters:(id)parameters
                                   success:(LZTResponseSuccess)success
                                   failure:(LZTResponseFailure)failure {
    NSURLSessionDataTask *dataTask = nil;
    AFHTTPSessionManager *magnager = [self managerRequest:URLString isJsonReponse:YES postHeadParameterMD5:@""];
    URLString  = [self package:URLString mamager:magnager parameters:parameters];
    parameters = [self parametserToJson:parameters];
    if(![self networkisReachable]){
        if (failure) {
            failure(nil);
        }
        return nil;
    }
    dataTask = [magnager PUT:URLString parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"url = %@ \n response = %@", URLString, [responseObject objectToJSON]);
        [self successResponse:responseObject callback:success];
        [[self allTasks] removeObject:task];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self faileureShowTip:failure error:error];
        [[self allTasks] removeObject:task];
    }];
    if (dataTask) {
        [[self allTasks] addObject:dataTask];
    }
    return dataTask;
}
+ (NSString *)package:(NSString *)url mamager:(AFHTTPSessionManager *)manager parameters:(NSDictionary *)parameters{
    url = url?url:@"";
    url = [self addCommontURLPrefix:url];
    NSLog(@"RequestURL:%@%@",manager.baseURL.absoluteString,url);
    //    NSLog(@"time = %@",[NetworkClock sharedNetworkClock].networkTime);
    if (parameters) {
        NSLog(@"Request params:%@",parameters);
    }
    return url;
}
+ (void)successResponse:(id)responseData callback:(LZTResponseSuccess)success {
    if (success) {
        //        NSLog(@"response = %@",[self tryToParseData:responseData]);
        success([self tryToParseData:responseData]);
    }
}

+ (id)tryToParseData:(id)responseData {
    

    if ([responseData isKindOfClass:[NSData class]]) {
        if (responseData == nil) {
            return responseData;
        } else {
            NSError *error = nil;
            NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseData
                                                                     options:NSJSONReadingMutableContainers
                                                                       error:&error];
            NSLog(@"<======json数据======>%@",[NSString df_dicBecomeJson:response]);
            
            if (error != nil) {
                return responseData;
            } else {
                return response;
            }
        }
    } else {
        
        
        return responseData;
    }
}

+ (NSMutableArray *) allTasks {
    static dispatch_once_t onceToken;
    static NSMutableArray *_requestTasks;
    dispatch_once(&onceToken, ^{
        if (_requestTasks == nil) {
            _requestTasks = [[NSMutableArray alloc] init];
        }
    });
    return _requestTasks;
}
+ (void)startRequestWithURL:(NSString *)url
                     method:(NSString *)method
                  paramters:(NSDictionary *)paramters
                    success:(LZTResponseSuccess)success
                    failure:(LZTResponseFailure)failure {
    
    NSURL *URL = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    //    [request setValue:@"ios" forHTTPHeaderField:@"os"];
    //    [request setValue:[[UIDevice currentDevice] systemVersion] forHTTPHeaderField:@"osVersion"];
    
    
    [request setValue:@"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    
    //    [request setValue:R([LDDeviceInfo version]) forHTTPHeaderField:@"version"];
    //    [request setValue:R([TVCUtils tvc_getDevUUID]) forHTTPHeaderField:@"uuid"];
    //    [request setValue:R([LDDeviceInfo deviceVersion]) forHTTPHeaderField:@"model"];
    
    //    if ([UserModel getUserEntity].token) {
    //        [request setValue:R([UserModel getUserEntity].token) forHTTPHeaderField:@"token"];
    //    }
    
    if ([method isEqualToString:@"POST"]) {
        if (paramters && paramters.count > 0) {
            
            //            NSDictionary * dictt = @{@"param":R([paramters objectToJSON])};
            NSString *str = [self postDataWithDic:paramters];
            // 创建请求体
            NSData * body = [str dataUsingEncoding:NSUTF8StringEncoding];
            [request setHTTPMethod:@"POST"];
            [request setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
            //            NSLog(@"原始长度 =%d",body.length);
            //            NSLog(@"压缩后长度 =%d",body.gzipDeflate.length);
            [request setHTTPBody:body];
            
        }
    }else {
        if (paramters && paramters.count > 0) {
            NSMutableString * str = [NSMutableString string];
            [str appendString:url];
            if (![str hasSuffix:@"?"]) {
                [str appendString:@"?"];
            }
            for (NSString * key in paramters) {
                [str appendFormat:@"%@=%@&", key, paramters[key]];
            }
            [str deleteCharactersInRange:NSMakeRange(str.length - 1, 1)];
            request.URL = [NSURL URLWithString:str];
        }
        
        
    }
    //推荐使用这种请求方法；
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            if (failure) {
                failure(error);
            }
        }
        if (data && [data isKindOfClass:[NSData class]]) {
            NSError *error = nil;
            NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data
                                                                     options:NSJSONReadingMutableContainers
                                                                       error:&error];
            TGResponseItem *responseItem = [TGResponseItem modelWithDictionary:response];
            if (!error) {
                if (success) {
                    success(responseItem);
                }
            }else{
                if (failure) {
                    failure(error);
                }
            }
        }
    }];
    [dataTask resume];
    
}

//上传图片
+ (void)uploadImage:(UIImage *)image filePath:(NSString *)filePath success:(LZTResponseSuccess)success failure:(LZTResponseFailure)failure {
//    NSString *url = [NSString stringWithFormat:@"%@%@", kApiBaseUrl, UploadImgUrl];
    
    NSString *url = StringFormat(APP_URL, @"api/public/file/upload");
//#if DEBUG
//    NSString *testUrl = [[NSUserDefaults standardUserDefaults] objectForKey:@"testUrl"];
//    if (!EmptyCheck(testUrl)) {
//        url = StringFormat(testUrl, @"/api/public/file/upload");
//    }
//#endif
    
    NSString *randomStr = [NSString stringWithFormat:@"%@%d", [NSString df_getCurrentTimestamp], arc4random()%1000];
    NSString *md5Str = [NSString md532BitLower:randomStr];
    
    AFHTTPSessionManager *magnager = [self managerRequest:url isJsonReponse:YES postHeadParameterMD5:md5Str];
    
    CGFloat imageW = image.size.width;
    CGFloat imageH = image.size.height;
    if (imageW > kMaxImageWidth || (image.size.height > kMaxImageWidth * 2 && imageH / imageW < 2)) {
        image = [image resizedImageToFitInSize:CGSizeMake(kMaxImageWidth, kMaxImageWidth * imageH / imageW) scaleIfSmaller:YES];
    }
    NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
    
    [magnager POST:url parameters:@{@"filePath": R(filePath)} headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"image.jpg" mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (!success)  return ;
        TGResponseItem *responseItem = [TGResponseItem modelWithDictionary:responseObject];
        NSLog(@"responseObject===%@", [responseObject objectToJSON]);

        if (responseItem.status == 401) {

            [self showLoginWithComplemention:^(NSString *result) {
//                NSString *randomStr = [NSString stringWithFormat:@"%@%d", [NSString df_getCurrentTimestamp], arc4random()%1000];
//                NSString *md5StrNew = [NSString md532BitLower:randomStr];
//                AFHTTPSessionManager *magnagerNew = [self managerRequest:url isJsonReponse:YES postHeadParameterMD5:md5StrNew];
//
//                [magnagerNew POST:url parameters:@{@"filePath": R(filePath)} headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//                    [formData appendPartWithFileData:imageData name:@"file" fileName:@"image.jpg" mimeType:@"image/jpeg"];
//                } progress:^(NSProgress * _Nonnull uploadProgress) {
//
//                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//                    TGResponseItem *responseItemNew = [TGResponseItem modelWithDictionary:responseObject];
//                    NSLog(@"responseObject===%@", [responseObject objectToJSON]);
//                    if (!responseItemNew.success && !EmptyCheck(responseItemNew.message)) {
//                        [TGGCD executeAfterTime:0.5 task:^{
//                            [TGProgressHUD showMBHUDErrorTip:responseItemNew.message];
//                        }];
//                    }
//                    [self successResponse:responseItemNew callback:success];
//
//                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//
//                }];
                [self successResponse:responseItem callback:success];
                [[self allTasks] removeObject:task];
            }];
            
            
        } else {
            if (!responseItem.success && !EmptyCheck(responseItem.message)) {
                [TGGCD executeAfterTime:0.5 task:^{
                    [TGProgressHUD showMBHUDErrorTip:responseItem.message];
                }];
            }
            [self successResponse:responseItem callback:success];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self faileureShowTip:failure error:error];
    }];
    
}


//上传视频
+ (void)uploadVideo:(NSString *)localPath filePath:(NSString *)filePath success:(LZTResponseSuccess)success failure:(LZTResponseFailure)failure {
    
    NSString *url = StringFormat(APP_URL, @"api/public/file/upload");
//#if DEBUG
//    NSString *testUrl = [[NSUserDefaults standardUserDefaults] objectForKey:@"testUrl"];
//    if (!EmptyCheck(testUrl)) {
//        url = StringFormat(testUrl, @"api/public/file/upload");
//    }
//#endif
    
    NSString *randomStr = [NSString stringWithFormat:@"%@%d", [NSString df_getCurrentTimestamp], arc4random()%1000];
    NSString *md5Str = [NSString md532BitLower:randomStr];
    
    AFHTTPSessionManager *magnager = [self managerRequest:url isJsonReponse:YES postHeadParameterMD5:md5Str];
    
//    NSData *imageData = videoData;
    
    [magnager POST:url parameters:@{@"filePath": R(filePath)} headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        [formData appendPartWithFileURL:[NSURL fileURLWithPath:localPath] name:@"file" fileName:@"video.mp4" mimeType:@"video/mp4" error:nil];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        double progress = 1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
        NSLog(@"$$$$$$$$$--%lf", progress);
        TGResponseItem *responseItem = [[TGResponseItem alloc] init];
        responseItem.success = NO;
        responseItem.uploadProgress = progress;
        [self successResponse:responseItem callback:success];
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (!success)  return ;
        TGResponseItem *responseItem = [TGResponseItem modelWithDictionary:responseObject];
        NSLog(@"responseObject===%@",responseObject);

        if (responseItem.status == 401) {

            [self showLoginWithComplemention:^(NSString *result) {
//                NSString *randomStr = [NSString stringWithFormat:@"%@%d", [NSString df_getCurrentTimestamp], arc4random()%1000];
//                NSString *md5StrNew = [NSString md532BitLower:randomStr];
//                AFHTTPSessionManager *magnagerNew = [self managerRequest:url isJsonReponse:YES postHeadParameterMD5:md5StrNew];
//
//                [magnagerNew POST:url parameters:@{@"filePath": R(filePath)} headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//
//                    [formData appendPartWithFileURL:[NSURL fileURLWithPath:localPath] name:@"file" fileName:@"video.mp4" mimeType:@"video/mp4" error:nil];
//
//                } progress:^(NSProgress * _Nonnull uploadProgress) {
//
//                    double progress = 1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
//                    NSLog(@"!!!!!--%lf", progress);
//                    TGResponseItem *responseItem = [[TGResponseItem alloc] init];
//                    responseItem.success = NO;
//                    responseItem.uploadProgress = progress;
//                    [self successResponse:responseItem callback:success];
//
//                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//                    TGResponseItem *responseItemNew = [TGResponseItem modelWithDictionary:responseObject];
//                    NSLog(@"responseObject===%@",responseObject);
//                    if (!responseItemNew.success && !EmptyCheck(responseItemNew.message)) {
//                        [TGGCD executeAfterTime:0.5 task:^{
//                            [TGProgressHUD showMBHUDErrorTip:responseItemNew.message];
//                        }];
//                    }
//                    [self successResponse:responseItemNew callback:success];
//
//                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//
//                }];
                [self successResponse:responseItem callback:success];
                [[self allTasks] removeObject:task];
            }];
            
            
        } else {
            if (!responseItem.success && !EmptyCheck(responseItem.message)) {
                [TGGCD executeAfterTime:0.5 task:^{
                    [TGProgressHUD showMBHUDErrorTip:responseItem.message];
                }];
            }
            [self successResponse:responseItem callback:success];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self faileureShowTip:failure error:error];
    }];
    
}


//识别身份证 0 或 营业执照 1
+ (void)recorginzedWithType:(NSInteger)type image:(UIImage *)image filePath:(NSString *)filePath success:(LZTResponseSuccess)success failure:(LZTResponseFailure)failure {
    
    NSString *url = StringFormat(APP_URL, @"thirdparty-service/api/m/ocr");
//#if DEBUG
//    NSString *testUrl = [[NSUserDefaults standardUserDefaults] objectForKey:@"testUrl"];
//    if ([testUrl containsString:@"192.168.7.146"]) {
//        url = @"http://192.168.7.146:30302/api/m/ocr";
//    } else if (!EmptyCheck(testUrl)) {
//        url = StringFormat(testUrl, @"thirdparty-service/api/m/ocr");
//    }
//#endif
    
//    NSString *url = @"http://192.168.1.62:30302/api/m/ocr/recognizeIdCard";
    
    if (type == 0) {
        url = [NSString stringWithFormat:@"%@/recognizeIdCard", url];
    } else if (type == 1) {
        url = [NSString stringWithFormat:@"%@/recognizeBusiness", url];
    }
    
    NSString *randomStr = [NSString stringWithFormat:@"%@%d", [NSString df_getCurrentTimestamp], arc4random()%1000];
    NSString*md5Str=[NSString md532BitLower:randomStr];
    
    AFHTTPSessionManager *magnager = [self managerRequest:url isJsonReponse:YES postHeadParameterMD5:md5Str];
    
    CGFloat imageW = image.size.width;
    CGFloat imageH = image.size.height;
    if (imageW > kMaxImageWidth || (image.size.height > kMaxImageWidth * 2 && imageH / imageW < 2)) {
        image = [image resizedImageToFitInSize:CGSizeMake(kMaxImageWidth, kMaxImageWidth * imageH / imageW) scaleIfSmaller:YES];
    }
    NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
    
    [magnager POST:url parameters:@{@"filePath": R(filePath)} headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"image.jpg" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (!success)  return ;
        TGResponseItem *responseItem = [TGResponseItem modelWithDictionary:responseObject];

        if (responseItem.status == 401) {
            
            [self showLoginWithComplemention:^(NSString *result) {
//                NSString *randomStr = [NSString stringWithFormat:@"%@%d", [NSString df_getCurrentTimestamp], arc4random()%1000];
//                NSString *md5StrNew = [NSString md532BitLower:randomStr];
//                AFHTTPSessionManager *magnagerNew = [self managerRequest:url isJsonReponse:YES postHeadParameterMD5:md5StrNew];
//
//                [magnagerNew POST:url parameters:@{@"filePath": R(filePath)} headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//                    [formData appendPartWithFileData:imageData name:@"file" fileName:@"image.jpg" mimeType:@"image/jpeg"];
//                } progress:^(NSProgress * _Nonnull uploadProgress) {
//
//                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//                    TGResponseItem *responseItemNew = [TGResponseItem modelWithDictionary:responseObject];
//                    NSLog(@"responseObject===%@",responseObject);
//                    if (!responseItemNew.success && !EmptyCheck(responseItemNew.message)) {
//                        [TGGCD executeAfterTime:0.5 task:^{
//                            [TGProgressHUD showMBHUDErrorTip:responseItemNew.message];
//                        }];
//                    }
//                    [self successResponse:responseItemNew callback:success];
//
//                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//
//                }];
                [self successResponse:responseItem callback:success];
                [[self allTasks] removeObject:task];
            }];
            
        } else {
            if (!responseItem.success && !EmptyCheck(responseItem.message)) {
                [TGGCD executeAfterTime:0.5 task:^{
                    [TGProgressHUD showMBHUDErrorTip:responseItem.message];
                }];
            }
            [self successResponse:responseItem callback:success];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self faileureShowTip:failure error:error];
    }];
    
}


//文件上传
+ (void)uploadFileWithFileUrl:(NSURL *)fileUrl
                     filePath:(NSString *)filePath
                      success:(LZTResponseSuccess)success
                      failure:(LZTResponseFailure)failure
{
    
    NSString *url = StringFormat(APP_URL, @"thirdparty-service/api/sys-upload/archive/uploadAudioFile");
//#if DEBUG
//    NSString *testUrl = [[NSUserDefaults standardUserDefaults] objectForKey:@"testUrl"];
//    if (!EmptyCheck(testUrl)) {
//        if ([testUrl containsString:@"192.168.7.146"]) {
//            url = @"http://192.168.7.146:30302/api/sys-upload/archive/uploadAudioFile";
//        } else if (!EmptyCheck(testUrl)) {
//            url = StringFormat(testUrl, @"thirdparty-service/api/sys-upload/archive/uploadAudioFile");
//        }
//    }
//#endif
    
    NSString *randomStr = [NSString stringWithFormat:@"%@%d", [NSString df_getCurrentTimestamp], arc4random()%1000];
    NSString*md5Str=[NSString md532BitLower:randomStr];
    
    AFHTTPSessionManager *magnager = [self managerRequest:url isJsonReponse:YES postHeadParameterMD5:md5Str];
    

    [magnager POST:url parameters:@{@"filePath": R(filePath)} headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileURL:fileUrl name:@"file" error:nil];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (!success)  return ;
        TGResponseItem *responseItem = [TGResponseItem modelWithDictionary:responseObject];

        NSLog(@"responseObject===%@",responseObject);
        
        if (responseItem.status == 401) {
            
            [self showLoginWithComplemention:^(NSString *result) {
//                NSString *randomStr = [NSString stringWithFormat:@"%@%d", [NSString df_getCurrentTimestamp], arc4random()%1000];
//                NSString *md5StrNew = [NSString md532BitLower:randomStr];
//                AFHTTPSessionManager *magnagerNew = [self managerRequest:url isJsonReponse:YES postHeadParameterMD5:md5StrNew];
//
//                [magnagerNew POST:url parameters:@{@"filePath": R(filePath)} headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//
//                    [formData appendPartWithFileURL:fileUrl name:@"file" error:nil];
//
//                } progress:^(NSProgress * _Nonnull uploadProgress) {
//
//                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//                    TGResponseItem *responseItemNew = [TGResponseItem modelWithDictionary:responseObject];
//                    NSLog(@"responseObject===%@",responseObject);
//                    if (!responseItemNew.success && !EmptyCheck(responseItemNew.message)) {
//                        [TGGCD executeAfterTime:0.5 task:^{
//                            [TGProgressHUD showMBHUDErrorTip:responseItemNew.message];
//                        }];
//                    }
//                    [self successResponse:responseItemNew callback:success];
//
//                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                    [self faileureShowTip:failure error:error];
//                }];
                [self successResponse:responseItem callback:success];
                [[self allTasks] removeObject:task];
            }];
            
            
        } else {
            if (!responseItem.success && !EmptyCheck(responseItem.message)) {
                [TGGCD executeAfterTime:0.5 task:^{
                    [TGProgressHUD showMBHUDErrorTip:responseItem.message];
                }];
            }
            [self successResponse:responseItem callback:success];
        }
            
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self faileureShowTip:failure error:error];
    }];
    
}



+ (void)uploadFileWithFileData:(NSData *)fileData
                      fileName:(NSString *)fileName
                      filePath:(NSString *)filePath
                      mimeType:(NSString *)mimeType
                       success:(LZTResponseSuccess)success
                       failure:(LZTResponseFailure)failure
{
    
    NSString *randomStr = [NSString stringWithFormat:@"%@%d", [NSString df_getCurrentTimestamp], arc4random()%1000];
    NSString*md5Str=[NSString md532BitLower:randomStr];
    
    NSString *url = StringFormat(APP_URL, @"thirdparty-service/api/sys-upload/uploadFile");
//#if DEBUG
//    NSString *testUrl = [[NSUserDefaults standardUserDefaults] objectForKey:@"testUrl"];
//    if (!EmptyCheck(testUrl)) {
//        if ([testUrl containsString:@"192.168.7.146"]) {
//            url = @"http://192.168.7.146:30302/api/sys-upload/uploadFile";
//        } else if (!EmptyCheck(testUrl)) {
//            url = StringFormat(testUrl, @"thirdparty-service/api/sys-upload/uploadFile");
//        }
//    }
//#endif
    
    AFHTTPSessionManager *magnager = [self managerRequest:url isJsonReponse:YES postHeadParameterMD5:md5Str];
    
    [magnager POST:url parameters:@{@"filePath": R(filePath)} headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        //给定数据流的数据名，文件名，文件类型
        [formData appendPartWithFileData:fileData name:@"file" fileName:fileName mimeType:mimeType];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (!success)  return ;
        TGResponseItem *responseItem = [TGResponseItem modelWithDictionary:responseObject];

        if (responseItem.status == 401) {

            [self showLoginWithComplemention:^(NSString *result) {
//                NSString *randomStr = [NSString stringWithFormat:@"%@%d", [NSString df_getCurrentTimestamp], arc4random()%1000];
//                NSString *md5StrNew = [NSString md532BitLower:randomStr];
//                AFHTTPSessionManager *magnagerNew = [self managerRequest:url isJsonReponse:YES postHeadParameterMD5:md5StrNew];
//
//                [magnagerNew POST:url parameters:@{@"filePath": R(filePath)} headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//
//                    [formData appendPartWithFileData:fileData name:@"file" fileName:fileName mimeType:mimeType];
//
//                } progress:^(NSProgress * _Nonnull uploadProgress) {
//
//                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//                    TGResponseItem *responseItemNew = [TGResponseItem modelWithDictionary:responseObject];
//                    NSLog(@"responseObject===%@",responseObject);
//                    if (!responseItemNew.success && !EmptyCheck(responseItemNew.message)) {
//                        [TGGCD executeAfterTime:0.5 task:^{
//                            [TGProgressHUD showMBHUDErrorTip:responseItemNew.message];
//                        }];
//                    }
//                    [self successResponse:responseItemNew callback:success];
//
//                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                    [self faileureShowTip:failure error:error];
//                }];
                [self successResponse:responseItem callback:success];
                [[self allTasks] removeObject:task];
            }];
            
            
        } else {
            if (!responseItem.success && !EmptyCheck(responseItem.message)) {
                [TGGCD executeAfterTime:0.5 task:^{
                    [TGProgressHUD showMBHUDErrorTip:responseItem.message];
                }];
            }
            [self successResponse:responseItem callback:success];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self faileureShowTip:failure error:error];
    }];
}


@end

